package com.qf.controller;

import org.apache.curator.shaded.com.google.thirdparty.publicsuffix.PublicSuffixPatterns;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.controller
 * @Description: 抢单
 * @Date 2022/8/17 18:03
 */
public class QiangDan {
    private static StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
    public static String main() throws Exception{
        String clientId = UUID.randomUUID().toString();
        String lockKey = "product_001";

        try {
            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 10, TimeUnit.MINUTES);
            if (!result){
                return "订单已被抢光";
            }

            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock>0){
                int realStock = stock-1;
                stringRedisTemplate.opsForValue().set("stock",realStock+"");
                System.out.println("扣减成功 ,剩余库存:"+realStock+"");
            } else {
                System.out.println("扣减失败, 库存不足");
            }
        } finally {
            if (clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))){
                //释放所
                stringRedisTemplate.delete(lockKey);
            }
        }
        return clientId;
    }
}
